package com.yinhai.util;

import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smackx.OfflineMessageManager;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.cmcc.groupcontacts.MainApp;
import com.littlec.sdk.XMPPConnectionManager;
import com.littlec.sdk.business.MessageConstants;
import com.littlec.sdk.entity.AckMessage;
import com.littlec.sdk.entity.CMGroup;
import com.littlec.sdk.entity.CMMember;
import com.littlec.sdk.entity.CMMessage;
import com.littlec.sdk.entity.SystemMessage;
import com.littlec.sdk.entity.messagebody.AudioMessageBody;
import com.littlec.sdk.entity.messagebody.ImageMessageBody;
import com.littlec.sdk.entity.messagebody.LocationMessageBody;
import com.littlec.sdk.manager.CMIMHelper;
import com.littlec.sdk.manager.HistoryMessageManager;
import com.littlec.sdk.utils.CMChatListener;
import com.littlec.sdk.utils.CMChatListener.CMMessageReceivedCallBack;
import com.littlec.sdk.utils.CMChatOfflineListener.CMOfflineMessageReceivedCallBack;
import com.littlec.sdk.utils.CMContactListener;
import com.yinhai.activity.LoadingActivity;
import com.yinhai.activity.R;
import com.yinhai.cfg.AppConfig;
import com.yinhai.cfg.LoginConfigUtil;
import com.yinhai.constant.Contact;
import com.yinhai.model.ContactsUser;
import com.yinhai.model.MsgModel;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.service.MsgServiceImpl;

/**
 * 小溪IM
 * 
 * @author lixh
 * 
 */
@SuppressLint("NewApi")
public class CMUtil {

	public static CMUtil cmUtil;

	private Context context;

	public static CMUtil getInstance(Context context) {

		if (cmUtil == null) {
			cmUtil = new CMUtil();
		}
		cmUtil.context = context;
		return cmUtil;
	}

	public void doLogout() {
		MainApp.isIMConnecteStatus = 0;
		CMIMHelper.getCmAccountManager().doLogOut();
	}

	public void doLogin() {
		SharedPreferences preferences = cmUtil.context.getSharedPreferences(
				AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
		Log.e("IM info", preferences.getString("name", "") + "=="
				+ preferences.getString("im_user_name", "") + "=="
				+ preferences.getString("im_user_password", ""));
		MainApp.isIMConnecteStatus = 1;
		CMIMHelper.getCmAccountManager().doLogin(
				preferences.getString("name", ""),
				preferences.getString("im_user_password", ""),
				new CMChatListener.OnCMListener() {

					@Override
					public void onSuccess() {
						// Util.showMsg(context, "登录成功");
						MainApp.isIMConnecteStatus = 2;
						setConctacListener();
						try {
							dealOfflineMsg();
						} catch (Exception e) {
							e.printStackTrace();
						}
						Intent intent = new Intent("com.im.login.success");
						context.sendBroadcast(intent);
					}

					@Override
					public void onFailed(String arg0) {
						// Log.e("im error", arg0);
						// Util.showMsg(context, "登录失败");
						MainApp.isIMConnecteStatus = 3;
						Intent intent = new Intent("com.im.login.error");
						context.sendBroadcast(intent);
					}
				});
	}

	/**
	 * 处理离线消息
	 */
	public void dealOfflineMsg() {
		// 处理离线消息类
		HistoryMessageManager.getInstance().setMessageCallBack(
				cmOfflineMessageReceivedCallBack);
		XMPPConnection connection = XMPPConnectionManager.getInstance()
				.getConnection();
		if (connection == null)
			return;
		OfflineMessageManager offlineManager = new OfflineMessageManager(
				connection);
		try {
			Iterator<org.jivesoftware.smack.packet.Message> it = offlineManager
					.getMessages();
			while (it.hasNext()) {
				org.jivesoftware.smack.packet.Message message = it.next();
				HistoryMessageManager.getInstance().dealOfflineMsg(message);
			}
			offlineManager.deleteMessages();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	CMOfflineMessageReceivedCallBack cmOfflineMessageReceivedCallBack = new CMOfflineMessageReceivedCallBack() {

		@Override
		public void onReceivedGroupChatMessage(CMMessage message) { // 群聊消息收到时候的处理代码
			Log.e("接收群消息", "===========");
			MsgServiceImpl msgServiceImpl = new MsgServiceImpl(cmUtil.context);
			ContactUserServiceImpl contactUserService = new ContactUserServiceImpl(
					cmUtil.context);
			ContactsUser sendContactsUser = contactUserService
					.findOnlineContactsUserByIMUserName(message.getFrom());
			if (sendContactsUser == null) {
				return;
			}
			// 接收消息
			if (message.getSendOrRecv() == MessageConstants.Message.MSG_RECV) {
				Log.e("接收群消息", "=====MSG_RECV======");
				MsgModel msgModel = null;
				// 群聊
				if (message.getChatType() == MessageConstants.Conversation.TYPE_GROUP) {
					String test = "";
					if (message.getGroupInfo() != null) {
						test = message.getGroupInfo().getGroupId();
					}
					Log.e("接收群消息", message.getFrom() + "===" + test);
					String groupName = CMIMHelper.getCmGroupManager()
							.getGroupNamefromServer(
									message.getGroupInfo().getGroupId());
					if (NullUtils.isEmpty(groupName)) {
						return;
					}
					msgModel = new MsgModel();
					msgModel.setRecId(message.getGroupInfo().getGroupId());
					msgModel.setRecName(groupName);
					msgModel.setGroupId(message.getGroupInfo().getGroupId());
					msgModel.setGroupName(groupName);
					msgModel.setSendUserId(sendContactsUser.getTelPhone());
					msgModel.setSendUserName(sendContactsUser.getName());
					msgModel.setIsGroup("1");// 群聊
					msgModel.setIsreceipt("0");
					handlerMessage(msgModel, message, msgServiceImpl);
				}
			}
		}

		@Override
		public void onReceivedChatMessage(CMMessage message) { // 单聊消息收到时候的处理代码

			MsgServiceImpl msgServiceImpl = new MsgServiceImpl(cmUtil.context);
			SharedPreferences preferences = cmUtil.context
					.getSharedPreferences(AppConfig.LOGIN_CONFIG,
							Context.MODE_PRIVATE);
			ContactUserServiceImpl contactUserService = new ContactUserServiceImpl(
					cmUtil.context);
			List<ContactsUser> contactUsers = contactUserService
					.findOnlineContactsUserByPhone(preferences.getString(
							"name", ""));
			ContactsUser sendContactsUser = contactUserService
					.findOnlineContactsUserByIMUserName(message.getFrom());
			if (NullUtils.isEmpty(contactUsers)
					|| NullUtils.isNull(sendContactsUser)) {
				return;
			}
			// 接收消息
			if (message.getSendOrRecv() == MessageConstants.Message.MSG_RECV) {
				MsgModel msgModel = null;

				// 单聊
				if (message.getChatType() == MessageConstants.Conversation.TYPE_SINGLE) {
					msgModel = new MsgModel();
					msgModel.setRecId(contactUsers.get(0).getTelPhone());
					msgModel.setRecName(contactUsers.get(0).getName());
					msgModel.setSendUserId(sendContactsUser.getTelPhone());
					msgModel.setSendUserName(sendContactsUser.getName());
					msgModel.setIsGroup("0");// 个人聊天
					msgModel.setIsreceipt("0");
					handlerMessage(msgModel, message, msgServiceImpl);

				}

				CMIMHelper.getCmMessageManager().sendMessage(
						new AckMessage(message.getFrom(), message.getGuid()),
						null);
			}

		}

		@Override
		public void onReceivedAckMessage(AckMessage message) {
			ContactUserServiceImpl contactUserService = new ContactUserServiceImpl(
					cmUtil.context);
			ContactsUser contactsUser = contactUserService
					.findOnlineContactsUserByIMUserName(message.getFrom());
			if (contactsUser == null) {
				return;
			}
			LoginConfigUtil.getConfig(cmUtil.context).getUsername();
			MsgServiceImpl msgServiceImpl = new MsgServiceImpl(cmUtil.context);
			msgServiceImpl.updateReceipt("1", message.getGuid() + "",
					LoginConfigUtil.getConfig(cmUtil.context).getUsername(),
					contactsUser.getTelPhone());
			MsgModel model = msgServiceImpl.findByGuid(message.getGuid() + "");
			if (model != null) {
				Intent intent = new Intent("com.im.messageresver");
				intent.putExtra("uuid", model.getUuid());
				cmUtil.context.sendBroadcast(intent);
			}
		}

		@SuppressWarnings("deprecation")
		@Override
		public void onReceivedToPullMessages(CMMessage message, int count) {
			Notification notification = null;
			PendingIntent pendingIntent = PendingIntent.getActivity(
					cmUtil.context, 0, new Intent(cmUtil.context,
							LoadingActivity.class),
					PendingIntent.FLAG_UPDATE_CURRENT);
			String content = "";

			if (message.getChatType() == MessageConstants.Conversation.TYPE_SINGLE) {
				content = message.getFromNick() + "等发来" + count + "条消息";
			} else if (message.getChatType() == MessageConstants.Conversation.TYPE_GROUP) {
				String groupName = CMIMHelper.getCmGroupManager()
						.getGroupNamefromServer(
								message.getGroupInfo().getGroupId());
				content = groupName + "等发来" + count + "条消息";
			}
			if (android.os.Build.VERSION.SDK_INT < 11) {
				notification = new Notification(R.drawable.ic_launcher,
						"集团通信录", System.currentTimeMillis());

				notification.setLatestEventInfo(cmUtil.context, "消息提醒",
						content, pendingIntent);
				notification.flags = Notification.FLAG_AUTO_CANCEL;
				notification.defaults |= Notification.DEFAULT_SOUND;
				notification.defaults |= Notification.DEFAULT_VIBRATE;
			} else {

				notification = new Notification.Builder(cmUtil.context)
						.setLargeIcon(
								BitmapFactory.decodeResource(
										cmUtil.context.getResources(),
										R.drawable.ic_launcher))
						.setSmallIcon(R.drawable.ic_launcher)
						.setTicker("集团通信录")
						.setContentTitle("消息提醒")
						.setContentText(content)
						.setContentIntent(pendingIntent)
						.setAutoCancel(true)
						.setDefaults(
								Notification.DEFAULT_VIBRATE
										| Notification.DEFAULT_SOUND).build();

			}

			NotificationManager nm = (NotificationManager) cmUtil.context
					.getSystemService(Activity.NOTIFICATION_SERVICE);

			nm.notify(1201, notification);

		}

		@Override
		public void onReceivedGroupChangeMessage(CMMessage message) {

		}
	};

	public void setConctacListener() {
		CMIMHelper.getCmAccountManager().addConnectionListener(
				new CMChatListener.OnConnectionListener() {

					@Override
					public void onReConnected() {
						MainApp.isIMConnecteStatus = 2;
					}

					@Override
					public void onDisConnected() {
						MainApp.isIMConnecteStatus = 0;
					}

					@Override
					public void onAccountDestroyed() {
						Util.showMsg(context, "你帐号后台删除，请联系管理员");
						MainApp.isIMConnecteStatus = 0;

					}

					@Override
					public void onAccountConflict() {
						Util.showMsg(context, "你帐号在别处登录");
						MainApp.isIMConnecteStatus = 4;
					}
				});
		CMContactListener cmContactListener = new CMContactListener() {

			@Override
			public void onContactAdded(String arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onContactAgreed(String arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onContactDeleted(String arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onContactInfoUpdated(String arg0, String arg1,
					String arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onContactInvited(String arg0, String arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onContactRefused(String arg0) {
				// TODO Auto-generated method stub

			}

		};

		CMMessageReceivedCallBack cmMessageReceivedCallBack = new CMMessageReceivedCallBack() {
			@Override
			public void onReceivedGroupChatMessage(CMMessage message) { // 群聊消息收到时候的处理代码
				Log.e("接收群消息", "===========");
				MsgServiceImpl msgServiceImpl = new MsgServiceImpl(
						cmUtil.context);
				ContactUserServiceImpl contactUserService = new ContactUserServiceImpl(
						cmUtil.context);
				ContactsUser sendContactsUser = contactUserService
						.findOnlineContactsUserByIMUserName(message.getFrom());
				if (sendContactsUser == null) {
					return;
				}
				// 接收消息
				if (message.getSendOrRecv() == MessageConstants.Message.MSG_RECV) {
					Log.e("接收群消息", "=====MSG_RECV======");
					MsgModel msgModel = null;
					// 群聊
					if (message.getChatType() == MessageConstants.Conversation.TYPE_GROUP) {
						String test = "";
						if (message.getGroupInfo() != null) {
							test = message.getGroupInfo().getGroupId();
						}
						Log.e("接收群消息", message.getFrom() + "===" + test);
						String groupName = CMIMHelper.getCmGroupManager()
								.getGroupNamefromServer(
										message.getGroupInfo().getGroupId());
						if (NullUtils.isEmpty(groupName)) {
							return;
						}
						msgModel = new MsgModel();
						msgModel.setRecId(message.getGroupInfo().getGroupId());
						msgModel.setRecName(groupName);
						msgModel.setGroupId(message.getGroupInfo().getGroupId());
						msgModel.setGroupName(groupName);
						msgModel.setSendUserId(sendContactsUser.getTelPhone());
						msgModel.setSendUserName(sendContactsUser.getName());
						msgModel.setIsGroup("1");// 群聊
						msgModel.setIsreceipt("0");
						handlerMessage(msgModel, message, msgServiceImpl);
					}
				}
			}

			@Override
			public void onReceivedChatMessage(CMMessage message) { // 单聊消息收到时候的处理代码

				MsgServiceImpl msgServiceImpl = new MsgServiceImpl(
						cmUtil.context);
				SharedPreferences preferences = cmUtil.context
						.getSharedPreferences(AppConfig.LOGIN_CONFIG,
								Context.MODE_PRIVATE);
				ContactUserServiceImpl contactUserService = new ContactUserServiceImpl(
						cmUtil.context);
				List<ContactsUser> contactUsers = contactUserService
						.findOnlineContactsUserByPhone(preferences.getString(
								"name", ""));
				ContactsUser sendContactsUser = contactUserService
						.findOnlineContactsUserByIMUserName(message.getFrom());
				if (NullUtils.isEmpty(contactUsers)
						|| NullUtils.isNull(sendContactsUser)) {
					return;
				}
				// 接收消息
				if (message.getSendOrRecv() == MessageConstants.Message.MSG_RECV) {
					MsgModel msgModel = null;

					// 单聊
					if (message.getChatType() == MessageConstants.Conversation.TYPE_SINGLE) {
						msgModel = new MsgModel();
						msgModel.setRecId(contactUsers.get(0).getTelPhone());
						msgModel.setRecName(contactUsers.get(0).getName());
						msgModel.setSendUserId(sendContactsUser.getTelPhone());
						msgModel.setSendUserName(sendContactsUser.getName());
						msgModel.setIsGroup("0");// 个人聊天
						msgModel.setIsreceipt("0");
						handlerMessage(msgModel, message, msgServiceImpl);

					}

					CMIMHelper.getCmMessageManager()
							.sendMessage(
									new AckMessage(message.getFrom(),
											message.getGuid(),message.getUuid()), null);
				}

			}

			@Override
			public void onReceivedCreateGroupMessage(CMMessage message,
					CMGroup cmGroup) { // XXX
										// 新建群的消息处理代码
			}

			@Override
			public void onReceivedExitGroupMessage(CMMessage message,
					String groupId) { // XXX
										// 退群消息处理代码
			}

			// }

			@Override
			public void onReceivedAddMembersMessage(CMMessage message,
					String groupId, List<CMMember> addedCMMembers) {
				// 群成员被 XXX 添加的处理代码
			}

			public void onReceivedSystemMessage(SystemMessage message) {
				// TODO Auto-generated method stub
				// 接收系统通知
			}

			@Override
			public void onReceivedSetGroupNameMessage(CMMessage arg0,
					String arg1, String arg2) {

			}

			@Override
			public void onReceivedAckMessage(AckMessage message) {
				ContactUserServiceImpl contactUserService = new ContactUserServiceImpl(
						cmUtil.context);
				ContactsUser contactsUser = contactUserService
						.findOnlineContactsUserByIMUserName(message.getFrom());
				if (contactsUser == null) {
					return;
				}
				LoginConfigUtil.getConfig(cmUtil.context).getUsername();
				MsgServiceImpl msgServiceImpl = new MsgServiceImpl(
						cmUtil.context);
				msgServiceImpl
						.updateReceipt("1", message.getMessageUuid(),
								LoginConfigUtil.getConfig(cmUtil.context)
										.getUsername(), contactsUser
										.getTelPhone());
				MsgModel model = msgServiceImpl.findByGuid(message.getMessageUuid());
				if (model != null) {
					Intent intent = new Intent("com.im.messageresver");
					intent.putExtra("uuid", model.getUuid());
					cmUtil.context.sendBroadcast(intent);
				}
			}

			@SuppressWarnings("deprecation")
			@Override
			public void onReceivedToPullMessages(CMMessage message, int count) {
				Notification notification = null;
				PendingIntent pendingIntent = PendingIntent.getActivity(
						cmUtil.context, 0, new Intent(cmUtil.context,
								LoadingActivity.class),
						PendingIntent.FLAG_UPDATE_CURRENT);
				String content = "";

				if (message.getChatType() == MessageConstants.Conversation.TYPE_SINGLE) {
					content = message.getFromNick() + "等发来" + count + "条消息";
				} else if (message.getChatType() == MessageConstants.Conversation.TYPE_GROUP) {
					String groupName = CMIMHelper.getCmGroupManager()
							.getGroupNamefromServer(
									message.getGroupInfo().getGroupId());
					content = groupName + "等发来" + count + "条消息";
				}
				if (android.os.Build.VERSION.SDK_INT < 11) {
					notification = new Notification(R.drawable.ic_launcher,
							"集团通信录", System.currentTimeMillis());

					notification.setLatestEventInfo(cmUtil.context, "消息提醒",
							content, pendingIntent);
					notification.flags = Notification.FLAG_AUTO_CANCEL;
					notification.defaults |= Notification.DEFAULT_SOUND;
					notification.defaults |= Notification.DEFAULT_VIBRATE;
				} else {

					notification = new Notification.Builder(cmUtil.context)
							.setLargeIcon(
									BitmapFactory.decodeResource(
											cmUtil.context.getResources(),
											R.drawable.ic_launcher))
							.setSmallIcon(R.drawable.ic_launcher)
							.setTicker("集团通信录")
							.setContentTitle("消息提醒")
							.setContentText(content)
							.setContentIntent(pendingIntent)
							.setAutoCancel(true)
							.setDefaults(
									Notification.DEFAULT_VIBRATE
											| Notification.DEFAULT_SOUND)
							.build();

				}

				NotificationManager nm = (NotificationManager) cmUtil.context
						.getSystemService(Activity.NOTIFICATION_SERVICE);

				nm.notify(1201, notification);

			}

			@Override
			public void onReceivedKickMemberMessage(CMMessage arg0,
					String arg1, CMMember arg2) {

			}

			@Override
			public void onReceivedMemberNickChangedMessage(
					CMMessage paramCMMessage, String paramString1,
					String paramString2) {

			}

			@Override
			public void onReceivedGroupChangeMessage(CMMessage paramGroupMessage) {
				// TODO Auto-generated method stub

			}

		};
		CMIMHelper.addListeners(cmContactListener, cmMessageReceivedCallBack);

	}

	private void handlerMessage(MsgModel msgModel, CMMessage message,
			MsgServiceImpl msgServiceImpl) {
		String uuid = UUID.randomUUID().toString();
		msgModel.setGuid(message.getGuid());
		msgModel.setUuid(uuid);

		msgModel.setSendDate(DateUtil.dateLongFormatString(message.getTime(),
				DateUtil.DAY_TIME_FORMATE));
		// 文本
		if (message.getContentType() == MessageConstants.Message.TYPE_TEXT) {

			msgModel.setContent(message.getMessageBody().getContent());
			// 文字类型
			msgModel.setConType(Contact.TEXT + "");
		} else if (message.getContentType() == MessageConstants.Message.TYPE_PIC) {
			ImageMessageBody body = (ImageMessageBody) message.getMessageBody();

			msgModel.setFileName(body.getMiddleUri());
			// 图片
			msgModel.setConType(Contact.PHOTO + "");

			// 位置
		} else if (message.getContentType() == MessageConstants.Message.TYPE_LOCATION) {
			LocationMessageBody body = (LocationMessageBody) message
					.getMessageBody();
			msgModel.setConType(Contact.POSMAP + "");
			msgModel.setLatitude(Double.valueOf(body.getLatitude()).toString());
			msgModel.setLongitude(Double.valueOf(body.getLongitude())
					.toString());
			msgModel.setContent(body.getAddress());
			msgModel.setFileName(body.getOriginalUri());

		} else if (message.getContentType() == MessageConstants.Message.TYPE_AUDIO) {
			AudioMessageBody body = (AudioMessageBody) message.getMessageBody();
			msgModel.setConType(Contact.REDIO + "");
			msgModel.setFileName(body.getFileName());
			msgModel.setSecond((body.getDuration()/1000) + "");
		}

		if (msgModel != null && NullUtils.isNotEmpty(msgModel.getConType())) {
			try {
				if (msgModel.getContent() != null
						&& (!"".equals(msgModel.getContent()))) {
					msgModel.setContent(StringUtilsSelf.iosFeel(msgModel
							.getContent()));
				}

				msgServiceImpl.saveIM(msgModel);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Intent mIntent = new Intent("com.im.message");
			mIntent.putExtra("data", msgModel);
			context.sendBroadcast(mIntent);
		}
	}
}
